package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import lombok.SneakyThrows;
import util.DBUtils;
import util.ResultUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @Author：fish
 * @Date：2023/4/3 12:23
 * 用户注册
 */
@WebServlet("/reg")
public class RegServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf-8");
        //返回的结果标识 1=注册成功，！=1注册失败
        int data = 0;
        String msg = "未知错误";
        //1.从前端得到参数
        String username =  req.getParameter("username");
        String nickname =  req.getParameter("nickname");
        String password =  req.getParameter("password");
        //1.1非空效验
        if (!StrUtil.isBlank(username) &&
                !StrUtil.isBlank(nickname) &&
                !StrUtil.isBlank(password)) {
            //2.将数据保存到数据库
            //2.1 得到连接
            //导入sql底下的connection包
            Connection connection = DBUtils.getConnection();
            //2.2 先判断登录名的唯一性
            String selSql = " select * from userinfo where username=?";
            //2.3 得到执行器
            PreparedStatement statement = connection.prepareStatement(selSql);
            statement.setString(1,username);
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                //当前用户名已存在
                msg = "您插入的登录名已存在，请更换登录名再试！";
            } else {
                // 拼接sql，并获得执行 【?:占位符】
                String sql = "insert into userinfo(username,nickname,password) values(?,?,?)";
                statement = connection.prepareStatement(sql);
                // 给执行器设置填充属性，并执行
                statement.setString(1,username);
                statement.setString(2,nickname);
                statement.setString(3, SecureUtil.md5(password));
                data = statement.executeUpdate();
            }
            // 关闭资源
            DBUtils.close(resultSet,statement,connection);
        } else {
            msg = "非法访问！";
        }
        //3.将数据库返回的结果返回给前端
        resp.getWriter().println(JSONUtil.toJsonStr(ResultUtils.toResult(200,data,msg)));
    }
}
